package zoo.reviewboard.user.controller;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import zoo.reviewboard.user.dao.ProductReviewBoardDao;
import zoo.reviewboard.user.domain.ProductReviewBoardCommand;
import zoo.util.FileUtil;

@Controller
public class ProductReviewBoardUpdateController {
	
	private String formViewName = "review_update";
	@Autowired
	private ProductReviewBoardDao prbDao;
		
	@RequestMapping(value="/main/reviewUpdate.do", method=RequestMethod.GET)
	public ModelAndView form(@RequestParam("pr_num") int pr_num){
		ProductReviewBoardCommand command = prbDao.selectReview(pr_num);
		return new ModelAndView(formViewName, "member", command);
	}
	
	@ModelAttribute("ProductReviewBoardCommand")
	public ProductReviewBoardCommand formBacking() {
		return new ProductReviewBoardCommand();
	}
	
	@RequestMapping(value="/main/reviewUpdate.do", method=RequestMethod.POST)
	public String submit(@ModelAttribute("command") ProductReviewBoardCommand command,
							@ModelAttribute("p_code")int p_code){

		
		ProductReviewBoardCommand board = null;
		String oldFileName = "";
		
			board = prbDao.selectReview(command.getPr_num());
			
			
				oldFileName = board.getPr_image();
				
				if(!command.getUpload().isEmpty()){
					//전송되어온 파일이 있을 경우
					try {
						command.setPr_image(FileUtil.rename(command.getUpload().getOriginalFilename()));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					//전송되어 온 파일이 없을 경우 기존 파일명 셋팅
					command.setPr_image(oldFileName);
				}
				
				prbDao.updateReview(command);
				
				if(!command.getUpload().isEmpty()){
					//전송되어온 파일 있을 경우
					try {
						File file = new File(FileUtil.UPLOAD_PATH + "/" + command.getPr_image());
						command.getUpload().transferTo(file);
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					if(oldFileName != null){
						//이전 파일 삭제
						FileUtil.removeFile(oldFileName);
					}
				}
			
		String formview = "redirect:/main/detailPro.do/p_code="+p_code; 
		
		
		
		return formview;
	}
	
}
